"""
HDF5 DAQ数据处理应用程序主入口点
连接UI和业务逻辑，使用信号与槽机制进行解耦
Author: Chengye Xu
"""

import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QObject, pyqtSlot

from ui.main_window import MainWindow
from core.data_processor import DataProcessor


class Application(QObject):
    """应用程序控制器，负责连接UI和业务逻辑"""
    
    def __init__(self):
        super().__init__()
        self.data_processor = DataProcessor()
        self.main_window = MainWindow()
        
        # 连接信号与槽
        self.connect_signals()
        
    def connect_signals(self):
        """连接UI信号与业务逻辑槽"""
        # 文件加载信号
        self.main_window.file_loaded.connect(self.on_file_loaded)
        
        # 绘图请求信号
        self.main_window.plot_requested.connect(self.on_plot_requested)
        
        # 预览请求信号
        self.main_window.preview_requested.connect(self.on_preview_requested)
        
        # 自动排序请求信号
        self.main_window.sorting_requested.connect(self.on_sorting_requested)
    
    @pyqtSlot(str)
    def on_file_loaded(self, file_path):
        """
        处理文件加载事件
        
        Args:
            file_path: 文件路径
        """
        try:
            result = self.data_processor.process_file_loaded(file_path)
            
            if result['success']:
                # 更新UI中的文件结构树
                self.main_window.update_file_tree(result['file_structure'])
                
                # 更新采样频率
                self.main_window.set_sampling_freq(result['sampling_freq'])
                
                # 更新幅度-相位配对列表
                self.main_window.update_amp_phase_pairs(result['amp_phase_pairs'])
                
                # 显示成功消息
                self.main_window.show_info_message("文件加载成功", result['message'])
            else:
                # 显示错误消息
                self.main_window.show_error_message("文件加载失败", result['message'])
                
        except Exception as e:
            self.main_window.show_error_message(
                "文件加载错误", 
                f"处理文件时出现意外错误: {str(e)}"
            )
    
    @pyqtSlot(dict)
    def on_plot_requested(self, parameters):
        """
        处理绘图请求
        
        Args:
            parameters: 绘图参数字典
        """
        try:
            result = self.data_processor.process_plot_request(parameters)
            
            if result['success']:
                # 显示成功消息
                self.main_window.show_info_message("绘图完成", result['message'])
            else:
                # 显示错误消息
                self.main_window.show_error_message("绘图失败", result['message'])
                
        except Exception as e:
            self.main_window.show_error_message(
                "绘图错误", 
                f"绘图过程中出现意外错误: {str(e)}"
            )
    
    @pyqtSlot()
    def on_preview_requested(self):
        """处理预览请求"""
        try:
            preview_text = self.data_processor.process_preview_request(
                self.main_window.current_file_path
            )
            self.main_window.show_preview_info(preview_text)
        except Exception as e:
            self.main_window.show_error_message(
                "预览错误", 
                f"无法预览文件: {str(e)}"
            )
    
    @pyqtSlot()
    def on_sorting_requested(self):
        """处理自动排序请求"""
        try:
            result = self.data_processor.process_sorting_request()
            
            if result['success']:
                # 更新UI中的幅度-相位配对列表
                self.main_window.update_amp_phase_pairs(result['sorted_pairs'])
                
                # 显示成功消息
                self.main_window.show_info_message("排序完成", result['message'])
            else:
                # 显示错误消息
                self.main_window.show_error_message("排序失败", result['message'])
                
        except Exception as e:
            self.main_window.show_error_message(
                "排序错误", 
                f"排序过程中出现意外错误: {str(e)}"
            )
            
    def run(self):
        """运行应用程序"""
        self.main_window.show()
        return QApplication.instance().exec_()
    
    def close_application(self):
        """关闭应用程序时的清理工作"""
        self.data_processor.close_file()


def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用程序信息
    app.setApplicationName("HDF5 LLRF Data Viewer (By Xu)")
    app.setApplicationVersion("1.0.0")
    app.setOrganizationName("LLRF Team")
    
    # 创建应用程序控制器
    application = Application()
    
    # 设置应用程序退出时的清理
    app.aboutToQuit.connect(application.close_application)
    
    # 运行应用程序
    exit_code = application.run()
    
    sys.exit(exit_code)


if __name__ == '__main__':
    main() 